﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Utility;

namespace System.DataProvider
{
    public class StoredProc
    {
        public string Name { get; set; }
        public string Identifier { get; set; }

        public List<Parameter> paras { get; set; }

        static List<StoredProc> list = null;
        public static void CreateList()
        {
            //list = null;
            if (list == null || bool.Parse(Settings.GetSettingByKey("RefreshDB")))
            {
                list = new List<StoredProc>();
                XmlDocument doc = Loader.LoadXmlDocument(Settings.GetSettingByKey("DBSource"));

                XmlNodeList procList = doc.GetElementsByTagName("StoredProc");

                foreach (XmlNode node in procList)
                {
                    StoredProc proc = new StoredProc();
                    proc.Name = node.Attributes["Name"].Value;
                    if (node.Attributes["Id"] != null)
                        proc.Identifier = node.Attributes["Id"].Value;
                    List<Parameter> paramsList = new List<Parameter>();
                    foreach (XmlNode paramNode in node.ChildNodes[0].ChildNodes)
                    {
                        Parameter param = new Parameter();
                        param.Name = paramNode.Attributes["Name"].Value;
                        paramsList.Add(param);
                    }
                    proc.paras = paramsList;
                    list.Add(proc);
                }
            }
        }

        public static StoredProc GetProc(string name)
        {
            StoredProc procToReturn = null;
            foreach (StoredProc proc in list)
            {
                if (proc.Name != name)
                    continue;
                else
                    procToReturn = proc;
                break;
            }
            return procToReturn;
        }

        public static string GetProcNameByIdentifier(string id)
        {
            StoredProc procToReturn = null;
            foreach (StoredProc proc in list)
            {
                if (string.IsNullOrEmpty(proc.Identifier) || proc.Identifier.ToLower() != id.ToLower())
                    continue;
                else
                    procToReturn = proc;
                break;
            }
            return procToReturn.Name;
        }


    }
}
